<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
	<meta name="apple-mobile-web-app-capable" content="no" />
	<title>地区选择</title>
	<link rel="stylesheet" href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/frame/mui/css/mui.min.css">
	<link rel="stylesheet" href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/frame/sui/css/SUI.css">
    <link rel="stylesheet" type="text/css" href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/font/iconfont.css">
    <link rel="stylesheet" type="text/css" href="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/css/index/area-select.css">
</head>
<body>
	<div class="head">
		<span id="back" class="back"></span>
		<div class="search-wrap">
			<span class="iconfont icon-search"></span>
			<input type="search" class="search" placeholder="城市">
		</div>
	</div>
	<div class="area-container">
		<div class="current">
			你正在看: 
		</div>
		<div class="aside-wrap">
			<span>定位</span>
			<span>热门</span>
		</div>
		<div class="content">
			<div class="block func">
				<span class="title">定位/最近访问</span>
				<div class="city-btn-wrap location">
					<span class="city-btn" id="location">
						<span class="iconfont icon-31dingwei"></span>
					</span>					
				</div>
			</div>
			<div class="block func">
				<span class="title">热门城市</span>
				<div class="city-btn-wrap hot-city">
					
				</div>
			</div>
		</div>
		<div class="cover"></div>
	</div>
	<script type="text/javascript" src="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/frame/mui/js/mui.min.js"></script>
	<script src="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/js/zepto.min.js"></script>
	<script src="https://tcsc.oss-cn-hangzhou.aliyuncs.com/static/wechat/js/area.js"></script>
	<script>
		const servedata = {{.citylist}},		//城市数组['',''],有店铺的城市为: '台州市1'
			  hotCity = {{.hotCity}},
			  mainShop = '台州市';	
		function AreaSort(arr) {		//城市按字母排序并分开
			this.arr = arr
		}
		AreaSort.prototype = {
			cutArr: function () {
				let str = '阿巴擦达额发噶哈叽咔拉妈那趴七冉撒他哇西压咋';
				return str.split('')
			},
			letterArr: function (t) {	//lower 小写, upper 大写
				let letter = 'abcdefghjklmnpqrstwxyz';
				t = t || 'lower'
				if (t == 'lower') {
					return letter.split('')
				}
				letter = letter.toLocaleUpperCase()
				return letter.split('')
			},
			sort: function (arr, method) {
		        if (!Array.isArray(arr)) 
		          return console.warn('require array type')
		      	if (!method)
		      		return arr.sort()
		        arr.sort(this.compare)
		    },
		    compare: function (a, b) {
		        if (typeof a !== 'string' && typeof b !== 'string') 
		          return console.warn('require string type')
		        return a.localeCompare(b, 'zh')
		    },
			res: function () {
				let letArr = this.letterArr('upper'),
					area = this.arr.concat(letArr),
					result = [];
				area = area.map(function (v) {
					let str = v
					if (v.substring(0, 1) === '长') {
						str = '常常' + str
					}
					let firstLetter = query(str)[0]
					str = firstLetter + str
					return str
				})
				this.sort(area)
				letArr.forEach(function (v, i, me) {
					const cell = {
						lett: v,
					};
					let begin = area.indexOf(v+v),
						end;
					if (i !== me.length) {
						end = area.indexOf(letArr[i+1]+letArr[i+1])
						cell.ctn = area.slice(begin + 1, end)
					} else {
						cell.ctn = area.slice(begin)
					}
					cell.ctn = cell.ctn.map(function(ctn) {
						ctn = ctn.substring(1)
						if (v == 'C') {
							if (ctn.substring(0,2) === '常常') {
								return ctn.substring(2)
							}
						}
						return ctn
					})
					result.push(cell)
				})
				return result
			}
		}
		AreaSort.prototype.constructor = AreaSort

		const city = new AreaSort(servedata)




		const f = {
			cell: function (el) {
				return document.querySelector(el)
			},
			all: function (el) {
				let els = Array.from(document.querySelectorAll(el)),
					i = 0;
				els.map(v => {
					v.index = i++
				})
				return els
			},
			element: function (t) {
				return document.createElement(t)
			},
			text: function (t) {
				return document.createTextNode(t)
			},
			changeCity: function (city) {
				if (!city) return mui.toast("暂无服务");
				this.visitCity(city)
				$.ajax({
					url: location.origin + '/changeShop',
					data: {
						city: city
					},
					success: function (res) {
						if (res.status == 1) {
							window.location.href = '/mobile/index?'+Date.now()
						}
					},
					error: function(xhr, type){
		                mui.toast("网络慢，请重试!");
		            }
				})
			},
			visitCity: function (city) {
				let cityList = localStorage.getItem('visitCityList');
				if (!cityList) return localStorage.setItem('visitCityList', city);
				let locationcity = sessionStorage.getItem('location') || mainShop,
					reg = new RegExp(city);
				if (reg.test(cityList)) return
				if (city === locationcity) return
				let arr = cityList.split(',');
				if (arr.length == 1) {
					arr.unshift(city)
					let str = arr.join(',');
					localStorage.setItem('visitCityList', str);
					return
				}
				arr[1] = arr[0]
				arr[0] = city
				let str = arr.join(',')
				localStorage.setItem('visitCityList', str);
			}
		};



		//开始渲染 添加事件
		(function (f, city) {
			const citylist = city.res();
			var str = "";
			let aside = f.cell('.aside-wrap'),
				arr = city.letterArr('upper'),
				currentCity = sessionStorage.getItem('currentCity') || "",
				shopArr = [];	

			f.cell('.current').innerText = '你正在看: ' + currentCity 	//当前城市

			let location = f.cell('.location'),		//定位,最近访问
				locationcity = sessionStorage.getItem('location') || mainShop,
				visitCity = localStorage.getItem('visitCityList'),
				span = f.element('span');
			span.appendChild(f.text(locationcity))
			f.cell('#location').appendChild(span)
			f.cell('#location').onclick = function () {
				f.changeCity(locationcity)
			}
			span = null
			if (visitCity) {
				let arr = visitCity.split(',');
				arr.map(function (v) {
					let span = f.element('span');
					span.city = v
					span.className = 'city-btn click'
					span.appendChild(f.text(v))
					location.appendChild(span)
				})
			}

			let hotCityWrap = f.cell('.hot-city');	//热门城市渲染	
			span = f.element('span')
			span.city = mainShop
			span.className = 'city-btn click'
			span.appendChild(f.text(mainShop))
			hotCityWrap.appendChild(span)
			span = null
			if (hotCity) {
				hotCity.map(function (v) {
					let span = f.element('span'),
						city = v.name;
					span.city = city
					span.className = 'city-btn click'
					span.appendChild(f.text(city))
					hotCityWrap.appendChild(span)
				})
			}

			arr.map(function (v) {		//右侧字母渲染
				let span = f.element('span');
				span.appendChild(f.text(v))
				aside.appendChild(span)		
			})

			let head = f.all('.aside-wrap span'),
				ctn = f.cell('.content'),
				container = f.cell('.area-container');

			citylist.map(function (v) {		//城市渲染
				let div = f.element('div'),
					span = f.element('span'),
					flag = false;
				div.className = 'block'
				span.className = 'title'
				span.appendChild(f.text(v.lett))
				div.appendChild(span)
				v.ctn.map(function (v) {
					let span = f.element('span'),
						text = v;
					if (text.endsWith('1')) {	//末尾为1是有店铺
						flag = true
						text = v.substring(0, v.length-1)
						shopArr.push(text)
						span.city = text
						text = text === mainShop ? text + '(总店)' : text
					} else {
						return
					}
					span.className = 'city click'
					span.appendChild(f.text(text))
					div.appendChild(span)
				})
				span.className += flag ? '' : ' none'
				ctn.appendChild(div)
			})

			ctn.onclick = function (e) {		//城市单击事件
				let target = e.target;
				if (target.nodeName.toLowerCase() !== 'span' || !/click/.test(target.className)) {
					return
				}
				let city = target.city || '';
				f.changeCity(city)
			}

			let area = f.all('.content .block');

			aside.onclick = function (e) {		//字母单击事件
				let curt = e.target;
				if (curt.nodeName.toLowerCase() == 'span') {
					let ctnDis = ctn.offsetTop,
						currentCityHeiht = f.cell('.current').offsetHeight,
						areaDis = area[curt.index].offsetTop + currentCityHeiht;
					container.scrollTop = areaDis - ctnDis
				}
			}

			let back = f.cell('#back');		//返回
			back.onclick = function () {
				window.location = '/mobile/index'
			}

			let search = f.cell('.search'),		//搜索
				cover = f.cell('.cover');		
			search.oninput = function (e) {
				let value = this.value.trim(),
					reg = new RegExp('^' + value),
					arr = [];
				cover.innerHTML = ''
				if (!value) return cover.style.display = 'none'
				cover.style.display = 'block'
				shopArr.map(function (v) {
					if (!reg.test(v)) return
					arr.push(v)
				})
				if (!arr.length) return cover.innerHTML = '<span class="no-found">抱歉,未找到相关的服务中心</span>'

				let div = f.element('div');
				div.className = 'city-wrap'
				arr.map(function (v) {
					let span = f.element('span'),
						text = v;
					span.city = text
					span.className = 'city'
					text = text === mainShop ? text + '(总店)' : text
					span.appendChild(f.text(text))
					div.appendChild(span)
				})
				cover.appendChild(div)
			}
			cover.onclick = function (e) {
				let target = e.target;
				if (target.className !== 'city') return
				let city = target.city || '';
				f.changeCity(city)
			}
		})(f, city);
	</script>
</body>
</html>